GBML manual / Sets

set_add

Adds value to target, a set, if it is not already a member. Returns true if target contains value AFTER this call - whether it was already there or was just added - false ONLY if value was new and target was already full (nothing changes - target never crashes or corrupts). Adding a value that is already a member is always safe and always reports true, never a failure.

Syntax

set_add(target, value) -> bool

Arguments

NameType
targetset
valueelement

Returns

bool

Description

Adds value to target, a set<T> - a container that only ever remembers WHICH values it has seen, never a position or a count. Returns true if target contains value AFTER this call - whether it was already there or was just added - false ONLY if value was new and target was already full (nothing changes - target never crashes or corrupts). Adding a value that is already a member is always safe and always reports true, never a failure.

target is a real fixed-size hash table that holds up to N items - N is target's own declared capacity (/// @capacity, default 8 if untagged), and it must always be a POWER OF TWO (2, 4, 8, 16, 32, ...) - its underlying storage (a hash table) requires it, the same rule map_set uses. The untagged default (8) already satisfies this.

T must be a type GBML can hash: int, real, bool, string, color, ref<obj>, or an asset id (sprite/sound/song/font/tileset/room/path/effect) - a struct cannot be a set's element, since the element IS the thing being hashed. The check happens where the variable is declared, not here.

set<T> has no [i] indexing - unlike array<T>/list<T>/grid<T>, a value is only ever reached through set_has, never by position. Declare the variable list<T> instead if you need to look inside it by position or keep duplicates.

Example

/// @type {set<int>}
var visited = [];
var added = set_add(visited, 5); // true - 5 is now a member
var added_again = set_add(visited, 5); // true - 5 was already a member, so nothing changed, but this still reports true
A real capture - an empty set, before set_add(visited, 5)A real capture - an empty set, before set_add(visited, 5)
A real capture - an empty set, before set_add(visited, 5)
The same set after set_add(visited, 5) - 5 is now a memberThe same set after set_add(visited, 5) - 5 is now a member
The same set after set_add(visited, 5) - 5 is now a member

On the GBA

The hash set's contains() then, only for a genuinely new value, a full()-guarded insert() - see this file's own Sets group header, "DUPLICATES AND THE RETURN VALUE", for why an existing member is checked FIRST rather than left to insert()'s own silent no-op. O(1) average.

See also: set_removeset_hasset_lengthset_clearData containers